from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.carts.utils import merge_cookie_redis_cart
from apps.oauth.models import OAuthQQUser


# qq登陆按钮点击视图
from apps.oauth.serializers import OAuthQQUserSerializer
from utils.openid_decode_encode import generate_sign_openid


class OAuthQQLoginView(APIView):
    def get(self,request):
        #获取state参数
        state=request.query_params.get("state","/")
        #初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        #获取QQ登录扫码页面
        login_url = oauth.get_qq_url()

        return  Response(data={"auth_url":login_url})

#qq登陆业务逻辑
class OAuthQQUserView(GenericAPIView):
    serializer_class = OAuthQQUserSerializer

    #判断用户是否已经绑定网站账号，有就登陆，没有就注册
    def  get(self,request):
        #获取code
        code=request.query_params.get("code")

        #判断code是否存在
        if not code:
            return Response("code已丢失")

        #创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state='/')

        #获取access_token
        access_token = oauth.get_access_token(code)

        #获取openid
        openid = oauth.get_open_id(access_token)

        #根据openid查询数据库，判断是否是初次授权
        try:
            oauth_qq_user=OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            #初次授权

            #加密openid
            encode_openid=generate_sign_openid(openid)
            #返回加密后的openid
            return Response({"access_token":encode_openid})

        else:
            #非初次授权，拿到用户对象
            user=oauth_qq_user.user

            #生成token
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)


            #组织返回数据
            data={
                "user_id":user.id,
                "username":user.username,
                "token":token
            }

            #创建响应体对象
            response=Response(data=data)
            #合并购物车
            merge_cookie_redis_cart(request, user, response)

            return response

    #qq登陆的注册
    def post(self, request):
        #反序列化
        serializer = self.get_serializer(data=request.data)
        #校验数据
        serializer.is_valid(raise_exception=True)
        #保存
        user = serializer.save()


        # 组织返回数据
        data = {
            "token": user.token,
            "user_id": user.id,
            "username": user.uskername
        }

        # 创建响应体对象
        response = Response(data=data, status=status.HTTP_201_CREATED)
        # 合并购物车
        merge_cookie_redis_cart(request, user, response)

        return response





